package thread;
class myBlockQueue {
    private String elem[] = new String[10];
    private volatile int size;
    private volatile int head = 0;
    private volatile int tail = 0;

    public void put(String val) {
        synchronized (this) {
            if(size == elem.length) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            elem[tail++] = val;
            size++;
            if (tail == elem.length) {
                tail = 0;
            }
            this.notify();
        }

    }

    public String take()  {
        synchronized (this) {
            if (size == 0) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            String ret = elem[head++];
            size--;
            if (head == elem.length) {
                head = 0;
            }
            this.notify();
            return ret;
        }

    }

}
public class demo4 {

    public static void main(String[] args) {
        myBlockQueue myBlockQueue = new myBlockQueue();
        Thread t1 = new Thread(() -> {
            int num = 1;
            while (true) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                myBlockQueue.put(num + "");
                System.out.println("生产num：" + num);
                num++;
            }
        });

        Thread t2 = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                String take = myBlockQueue.take();
                System.out.println("消费num：" + take);
            }
        });

        t1.start();
        t2.start();
    }
}
